#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################
# @Author: DengLibin 榆霖
# @Date: Create in 2022-03-16 17:09:07
# @Description: 中文文档 https://www.cntofu.com/book/170/docs/79.md
##############################################

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score


def run():
    df = pd.read_csv('generation_data.csv')
    # print(df.to_string())
    x = df.loc[:, 'x']
    y = df.loc[:, 'y']
    
    # 线性回归模型
    lr_model = LinearRegression()
    
    x = np.array(x)
    # 转为5行1列
    x = x.reshape(-1, 1)

    y = np.array(y)
    y = y.reshape(-1, 1)
    
    # 模型拟合
    lr_model.fit(x, y)
    # 使用模型根据x预测y
    y_predict = lr_model.predict(x)
    
    # 打印预测结果
    print(y_predict)
    print('-------------------------------------')
    # 真实结果
    print(y)
    
    print('----------------预测一下3.5---------------------')
    y_3 = lr_model.predict([[3.5]])
    print(y_3)
    
    print('----------------获取y=ax+b的 a和b的值---------------------')
    a = lr_model.coef_
    b = lr_model.intercept_
    print(a, b)
    
    # MSE 均方误差 越接近0越好，模型越准确
    MSE = mean_squared_error(y, y_predict)
    print(MSE)
    # r方 越接近1越好
    R2 = r2_score(y, y_predict)
    print(R2)
    
    # plt.figure(figsize=(10, 10), dpi=100);
    # plt.scatter(x, y)
    # plt.show()
    
if __name__ == '__main__':
   run()
